import React,{Component} from "react"

import {Link} from "react-router-dom";
import BScroll  from "better-scroll";

import Loading from "../../components/loading"

import img1 from "../../images/num1.png"
import img2 from "../../images/num2.png"
import img3 from "../../images/num3.png"
import shareImg from "../../images/share.png"

import "./index.css"

import {getCourseList,getRankList,authLogin,updateUserinfo} from "../../api/course"

function toZero(n){
  return n>9 ? ""+n:"0"+n
}



class Index extends Component{
    constructor(props){
    	super(props);
    	this.state = {
            nowIndex:0,
            tabbar:["热门","导师排行"],
            hotlist:[],
            ranklist:[],
            hotPage:0,
            nowDate:"",
            showLoading:true,
            showTost:false
    	}
    }

    

    getUserInfo(){
       if(window.location.href.split("?")[1] && window.location.href.indexOf("from=groupmessage")==-1){
       
            var arr1 = window.location.href.split("?")[1];
            var authResult;

            try {
                authResult = JSON.parse(decodeURIComponent(arr1.split("&")[1].split("=")[1]).replace('#/',''));
            } catch (err) {
                var url = decodeURI(decodeURI(window.location.href));
                var authResultStr = url.split("&jxweibo=")[1];
                if(authResultStr){
                   authResult = JSON.parse(authResultStr.replace('#/', ''));
                }
            }

            if(!window.queryString('accessToken')){
                  var provider ;
                  if(window.queryString('jxqq')){
                       provider = 6;
                  }else if(window.queryString('jxweibo')){
                           provider = 4;
                  }else if(window.queryString('jxwechat')){
                       provider = 5;
                  }else if(window.queryString('jxopenwechat')){
                        provider = 5;
                  }
                 

                  authLogin({
                      "DeviceType": 6,
                      "DeviceId": new Date().getTime().toString(),
                      "Provider": provider,//window.queryString('jxqq')!=null?6:4,
                      "ProviderUserId": authResult.openid,
                      "AccessToken": authResult.access_token,
                      "Profile": {
                          "NickName": authResult.nickname,
                          "Name": authResult.nickname,
                          "ImageUrl": authResult.avator||authResult.headimgurl
                      }
                  }).then(res => {
                        console.log(res.data)
                        localStorage.setItem("courseUserinfo", JSON.stringify(res.data));
                        let {AccessToken,NickName} = res.data;
                        
                        updateUserinfo(AccessToken,res.data)
                        .then(res=>{
                          console.log(res);
                          
                          this.setState({showTost:true},()=>{
                             setTimeout(()=>{
                               this.setState({showTost:false})
                               window.location.href = "https://apps.ixingban.com/fanscourse";
                             },2000)
                          })
                        }).catch(err=>{
                           //alert("用户昵称不合法");
                           window.location.href = "https://apps.ixingban.com/fanscourse/edit"
                        })
                    
                  })
            }else{
              // let accessToken = window.queryString('accessToken');
               
            }

        }
    }
    

    

    componentDidMount(){
        //window.location.href = "https://games.ixingban.com/fanscourse/#/";     
        this.loadHot();
        this.loadRank();
        this.gethotlist(0,10);
        this.getRanklist(0);
        this.getDate();
    	  this.getUserInfo();
        window.WechatInit(encodeURIComponent(window.location.href)).then(wx=>{
              //alert(JSON.stringify(wx))
              //alert(window.location.href)
              var shareOptions = { 
                  title:"粉丝课", // 分享标题
                  desc:"粉丝课", // 分享描述
                  link:window.location.href,//window.location.href,//"https://games.ixingban.com/fanscourse/#/detail/"+180018//window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                  imgUrl: "https://blob.ixingban.com/fanscourse/32377e7dc45a40898a98cc1611d699a6.png", // 分享图标
                  success: function (res) {
                     //alert(JSON.stringify(res))
                     //console.log(res);
                  }
              }
              
              if(wx){
                 wx.updateAppMessageShareData(shareOptions);
                 wx.updateTimelineShareData(shareOptions);
                 wx.onMenuShareWeibo(shareOptions);
              }
          })

    }

    getDate(){
        this.setState({
           nowDate:new Date().getFullYear()+"-"+toZero((new Date().getMonth()+1))+"-"+toZero(new Date().getDate())
        })
    }

    getRanklist(){
      getRankList(0).then(res=>{
         let ranklist = JSON.parse(res.data.data.data);
         this.setState({
            ranklist
         })
      })
    }
    
    
    gethotlist(page){
      getCourseList(page,10).then(res=>{
         this.setState({
            showLoading:false,
            hotlist:[...this.state.hotlist,...res.data]
         })
      })
    }



    loadHot(){
    	  this.hot = new BScroll(this.refs.hot,{
            scrollY: true,
            click: true,
            useTransition:false,
            pullUpLoad: {
              threshold:-20 
            },
            pullDownRefresh: {
               threshold:30,
               stop: 0
            }
        })
        
        
        this.hot.on('pullingUp',()=>{
            //console.log("到底部了")
            this.setState({
               hotPage:this.state.hotPage+10
            },()=>{
              this.gethotlist(this.state.hotPage)
            })
            
            setTimeout(() => {
                this.hot.finishPullUp();
                this.hot.refresh();
            },500)
         
        })
    }

    loadRank(){
        this.ranklist = new BScroll(this.refs.ranklist,{
            scrollY: true,
            click: true,
            useTransition:false,
            pullUpLoad: {
              threshold:-20 
            },
            pullDownRefresh: {
               threshold:30,
               stop: 0
            }
        })
        
        
        this.ranklist.on('pullingUp',()=>{
            setTimeout(() => {
                this.ranklist.finishPullUp();
                this.ranklist.refresh();
            },500)
        })
    }


    tabHandl(nowIndex){
    	 this.setState({
    	 	nowIndex
    	 })
    }

	render(){
		let {tabbar,nowIndex,ranklist,hotlist,nowDate} = this.state;
		return(
            <div className="indexpage">
                <div className="tab">
                    {tabbar.map((item,index) => <span key={index} 
                    	                              className={nowIndex===index?"active":""} 
                    	                              onClick={this.tabHandl.bind(this,index)}>
                    	                              {item}
                                                    <em></em>
                    	                        </span>)}
                </div>
                
                <div className="hot" ref="hot" style={{"opacity":nowIndex===0?1:0,"zIndex":nowIndex===0?10:9}}>
                    <ul>
                        {hotlist.map((item,index)=>{
                           return  <li key={index} onClick={()=>{this.props.history.push("/fanscourse/detail/"+item.PostId+"?nowindex=0")}}>
                                    <img src={item.PhotoList[0].ThumbnailUrl} alt=""/>
                                    <p>{item.Title}</p>
                                  </li>
                        })}
                    </ul>
                </div>

  
                <div className="rank"  style={{"opacity":nowIndex===1?1:0,"zIndex":nowIndex===1?10:9}}>
                    <div className="rank-box">
                          <div className="top">
                              <div className="titleimg"></div>
                              <p>数据更新时间：{nowDate}</p> 
                              <div className="rankbg"></div>
                          </div>
                          <div className="ranklist" ref="ranklist">
                          <ul>
                             {ranklist.map((item,index)=>{
                                return <li key={index}>
                                    {index===0?<img src={img1} alt="" className="numimg"/>:null}
                                    {index===1?<img src={img2} alt="" className="numimg"/>:null}
                                    {index===2?<img src={img3} alt="" className="numimg"/>:null}
                                    {index>2?<span className="numtext">{index+1}</span>:null}
                                <dl>
                                   <dt>
                                      <img src={item.imgurl} alt=""/>
                                   </dt>
                                   <dd>
                                        <div>
                                            <h3>{item.coursetutor}</h3>
                                            <em>@{item.coursetutor}</em>
                                        </div>
                                        <p>
                                           <span>总热度：{item.heatcount}</span>
                                           <span>播放指数：{item.watchcount}</span>
                                           <span>分享指数：{item.platcount}</span>
                                           <span>阅读指数：{item.readcount}</span>
                                        </p>
                                   </dd>
                               </dl>
                            </li>})}
                          </ul>
                             
                        </div>   
                    </div>


                </div>
                {this.state.showLoading?<Loading />:null}
                
                {this.state.showTost?<p className="tost"><span>登录成功</span></p>:null}
            </div>
		)
	}
}


export default Index